<template>
  <div>
    <el-upload
      class="avatar-uploader"
      :show-file-list="false"
      action=""
      :http-request="uploadImg"
      accept="image/*"
    >
      <img v-if="staffPhoto" :src="staffPhoto" class="avatar">
      <i v-if="iconVisible" ref="icon" class="el-icon-plus avatar-uploader-icon" />
      <el-progress
        v-if="progressVisible"
        type="circle"
        :percentage="percentage"
        :width="178"
        style="float: left"
      />
    </el-upload>
  </div>
</template>
<script>
// sdk software development kit 软件开发工具集
import COS from 'cos-js-sdk-v5'
const cos = new COS({
  SecretId: 'AKIDQhmdFckeJk4KUTGqCLPRHsStYjjW7Ufc',
  SecretKey: 'lGZfblojU6XZUItHUWM0UmsmU0KSN6dx'
}) // 完成cos对象的初始化
export default {
  name: 'UploadImg',
  props: {
    staffPhoto: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      percentage: 0,
      progressVisible: false,
      iconVisible: true,
      loading: false
    }
  },
  watch: {
    staffPhoto(val) {
      if (this.loading) {
        // console.log(111)
        return
      }
      this.iconVisible = !val
    }
  },
  methods: {
    // 上传图片接口
    async uploadImg(file) {
      this.progressVisible = true
      this.loading = true
      this.iconVisible = false
      // console.log(this.iconVisible)
      this.$emit('update:staffPhoto', '')
      cos.putObject(
        {
          Bucket: 'robot-1318751017', // 存储桶名称
          Region: 'ap-nanjing', // 地域名称
          Key: file.file.name, // 文件名称
          StorageClass: 'STANDARD', // 固定值
          Body: file.file, // 文件对象
          onProgress: (progressData) => {
            this.percentage = 0
            // 上传进度
            // console.log(JSON.stringify(progressData))
            this.percentage = parseInt(progressData.percent * 100)
          }
        },
        (err, data) => {
          if (data.statusCode === 200 && data.Location) {
            // 拿到了腾讯云返回的地址
            // 通过input自定义事件将地址传出去
            this.progressVisible = false
            this.loading = false
            this.$emit('update:staffPhoto', 'http://' + data.Location) // 将地址返回了
          } else {
            this.loading = false
            this.progressVisible = false
            this.$message.error(err.message) // 上传失败提示消息
          }
        }
      )
    }
  }
}
</script>
<style lang='scss'  scoped>
:deep(.avatar-uploader) .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

</style>
